import { ref } from 'vue'
import {getPostgres as getPostgresApi,
  gettotalArea as gettotalAreaApi,
  getPostgresInfo as getPostgresInfoApi,
  putPostgresInfo as putPostgresInfoApi,
  detPostgresInfo as detPostgresInfoApi,
  getGeojson as getGeojsonApi,
  getTownAndVillage as getTownAndVillageApi,
} from '@/api/tab';
import { LoginData } from '@/api/types';
import { defineStore } from 'pinia'
import { log } from 'echarts/types/src/util/log.js';
import * as mars3d from "mars3d"
import { download } from '@/utils/request';

export const useTabStore = defineStore('tab', () => {
  const queryParams = ref({
    pageSize:10,
    pageNum:1,
    isAsc:'desc',
    orderByColumn:'update_time',
    townName:'',
    villageName:'',
    farmName:'',
    contractorName: '',
    isFarm: '0',
    circulationTime:''
  });
  const total = ref(0);
  const tabData = ref()
  const form = ref<any>({})
  const detGid = ref<any>()
  const webtabelHeight = ref<number>(0)
  const mobtabelHeight = ref<number>(0)
  const clFlag = ref<boolean>(false)

  const townName = ref<string>('')
  const totalArea = ref<number>(0)
  const isLayerLoading = ref<boolean>(false)
  const townArr = ref<any>([])
  const townValue = ref<any>([])
  const townEditValue = ref<any>([])

  const props1 = {
    checkStrictly: true,
    value:'name',
    label:'name',
    children:'villageVoList'
  }
  /**
   * 登录
   * @param userInfo
   * @returns
   */
  const getPostgres = () => {
    if (queryParams.value.isFarm=='1') {
      queryParams.value.isFarm=''
    }
    getPostgresApi(queryParams.value).then(res => {
      if(res.code == 200) {
        tabData.value = res.rows
        total.value = res.total
        webtabelHeight.value = window.innerHeight - 110 - document.getElementById('webtabSearch').offsetHeight;
        mobtabelHeight.value = window.innerHeight - 110 - document.getElementById('mbtabsearch').offsetHeight;
        window.addEventListener('resize', function() {
          webtabelHeight.value = window.innerHeight - 110 - document.getElementById('webtabSearch').offsetHeight;
          mobtabelHeight.value = window.innerHeight - 110 - document.getElementById('mbtabsearch').offsetHeight;
        });

        gettotalAreaApi(queryParams.value).then(res => {
          totalArea.value = res
        })
      }
    })
  };

  const getPostgresInfo = (gid) => {
    getPostgresInfoApi(gid).then(res => {
      form.value = res.data
      townEditValue.value = [res.data.townName,res.data.villageName]
    })
  };

  const putPostgresInfo = async () => {
      await putPostgresInfoApi(form.value).then(res=>{
      if(res.code == 200) {
        ElMessage({ message: res.msg, type: 'success' })
        getPostgres()
        getGeojsonApi(form.value.gid).then(element => {
          window.PolyhonLayer.clear()
          let PolyhonEntity = new mars3d.graphic.PolygonEntity({
            positions:JSON.parse(element.msg).coordinates[0][0],
            style:{
              fill:false,
              color:'#1d9bf0',
              outline:true,
              outlineWidth:3,
              outlineColor:'#ff0000',
              label:{
                text:'承包人:' + form.value.contractorName,
                color:'#ff0000',
              },
            },
            flyTo:true,
            flyToOptions:{
              minHeight:1000,
              duration:2
            }
          })
          PolyhonEntity.addTo(window.PolyhonLayer)
        })
      }else {
        ElMessage({ message: res.msg, type: 'error' })
      }
    })
  }

  const detPostgresInfo = async () => {
    await detPostgresInfoApi(detGid.value).then(res=>{
      if(res.code == 200) {
        ElMessage({ message: res.msg, type: 'success' })
        getPostgres()
        window.sytdlzwma.reload()
      }else {
        ElMessage({ message: res.msg, type: 'error' })
      }
    })
  }

  const searchPostgresInfo = () => {
    queryParams.value.contractorName = queryParams.value.contractorName.trim();
    queryParams.value.villageName = queryParams.value.villageName.trim();
    queryParams.value.farmName = queryParams.value.farmName.trim();
    queryParams.value.townName = queryParams.value.townName.trim();
    if (queryParams.value.circulationTime==null) {
      queryParams.value.circulationTime = ''
    }
    getPostgres()
    let timer = setInterval(()=> {
      window.sytdlzwma?.setOptions({
        parameters: {
          service:'WMS',
          version:'1.1.1',
          request:'GetMap',
          transparent: true,
          format: "image/png",
          cql_filter: queryParams.value.farmName.length>0?
          `where contractor_name like '%${ queryParams.value.contractorName }%' and village_name like '%${ queryParams.value.villageName }%' and farm_name like '%${ queryParams.value.farmName }%' and town_name like '%${ queryParams.value.townName }%' and circulation_time like '%${ queryParams.value.circulationTime}%'`:
          `where contractor_name like '%${ queryParams.value.contractorName }%' and village_name like '%${ queryParams.value.villageName }%' and town_name like '%${ queryParams.value.townName }%' and circulation_time like '%${ queryParams.value.circulationTime }%'`
        },
      })
      clearInterval(timer)
    },100)
  }


  const resetQuery = () => {
    queryParams.value = {
      pageSize:10,
      pageNum:1,
      isAsc:'desc',
      orderByColumn:'update_time',
      townName:'',
      villageName:'',
      farmName:'',
      contractorName: '',
      isFarm: '0',
      circulationTime:''
    }
    townValue.value = []
    getPostgres()
    let timer = setInterval(()=> {
      window.sytdlzwma.setOptions({
        parameters: {
          service:'WMS',
          version:'1.1.1',
          request:'GetMap',
          transparent: true,
          format: "image/png",
          cql_filter: queryParams.value.farmName.length>0?
          `where contractor_name like '%${ queryParams.value.contractorName }%' and village_name like '%${ queryParams.value.villageName }%' and farm_name like '%${ queryParams.value.farmName }%' and town_name like '%${ queryParams.value.townName }%'`:
          `where contractor_name like '%${ queryParams.value.contractorName }%' and village_name like '%${ queryParams.value.villageName }%' and town_name like '%${ queryParams.value.townName }%'`
        },
      })
      clearInterval(timer)
    },100)
  }

  const getTownAndVillage = async () => {
    await getTownAndVillageApi().then(res => {
      townArr.value = res
    })
  }

  const changeXZQ = (node) => {
    queryParams.value.townName = ''
    queryParams.value.villageName = ''
    if(node!=null){
      if(node.length==1) {
        queryParams.value.townName = node[0]
      }else if(node.length==2) {
        queryParams.value.townName = node[0]
        queryParams.value.villageName = node[1]
      }
    }
    searchPostgresInfo()
  }

  const getExport = async () => {
    download('/business/sytdlz/export', {
      ...queryParams.value
    }, `射阳土地流转${new Date().getTime()}.xlsx`)
  }

  return {
    queryParams,
    total,
    tabData,
    form,
    detGid,
    webtabelHeight,
    mobtabelHeight,
    clFlag,
    townName,
    totalArea,
    townArr,
    props1,
    townValue,
    isLayerLoading,
    townEditValue,
    getPostgres,
    getPostgresInfo,
    putPostgresInfo,
    detPostgresInfo,
    searchPostgresInfo,
    resetQuery,
    getTownAndVillage,
    changeXZQ,
    getExport,
  };
});

export default useTabStore;
// 非setup
export function useTabStoreHook() {
  return useTabStore(store);
}
